import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:package_info/package_info.dart';
import 'dart:io';
import 'package:device_info/device_info.dart';
import 'package:riki_login/api/base_api.dart';
import 'package:riki_login/api/oauth/oauth_api.dart';
import 'package:riki_login/api/sms/sms_api.dart';
import 'package:riki_login/config/global.dart';
import 'package:riki_login/entity/check_sms_code_req_entity.dart';

import '../../riki_login.dart';

///作者：范玉辉
///创建时间：2020/12/15
///说明：验证码登录状态管理

class UserLoginCodeViewModel extends SingleViewStateModel {
  late SmsUserCheckCodeApi smsCheckCodeApi; // 验证验证码
  late NetEaseSendSmsApi netEaseSendSmsApi; // 发送验证码
  late UserLoginRecordApi _userLoginRecordApi;
  String userPhone = ''; //手机号
  String userCode = ''; // 验证码
  Timer? _timer; //定义变量

  ///用于获取验证码按钮的局部刷新
  String sendCode = '获取验证码';
  int phoneLen = 0;

  // 埋点相关
  late Map<String, dynamic> param;

  ///获取验证码按钮是否可用
  void refreshFetchCodeBtn(int len) {
    phoneLen = len;
    notifyListeners(refreshVM: false);
  }

  //String sendCode = '获取验证码';
  var countdownTime = 0; //倒计时数值

  void setUserCode(String code) {
    userCode = code;
    checkInputText();
  }

  void setUserPhone(String phone) {
    userPhone = phone;
    checkInputText();
    refreshFetchCodeBtn(userPhone.length);
  }

  //是否显示输入框尾部的清除按钮
  bool isShowClear = false;

  void setShowClear(bool show) {
    isShowClear = show;
    notifyListeners(refreshVM: false);
  }

  ///是否设置登录按钮可用
  bool loginBtnEnable = false;

  void switchLoginBtn(bool status) {
    loginBtnEnable = status;
    notifyListeners(refreshVM: false);
  }

  ///用于检查用户输入手机号或验证码时，登录按钮是否可用
  void checkInputText() {
    if (loginBtnEnable != (userPhone.length == 11 && userCode.length > 0)) {
      switchLoginBtn(userPhone.length == 11 && userCode.length > 0);
    }
  }

  // 是否可以登录
  bool isTap = false;

  ///初始化api
  void initApi(BuildContext context) {
    netEaseSendSmsApi = NetEaseSendSmsApi(context);
    smsCheckCodeApi = SmsUserCheckCodeApi(context, userPhone, userCode);
    _userLoginRecordApi = UserLoginRecordApi(context);
  }

  /// 验证验证码
  Future<void> checkCode() async {
    Completer completer = Completer();
    smsCheckCodeApi
        .start(
      params: CheckSmsCodeReqEntity(
        phone: this.userPhone,
        code: userCode,
        deviceId: await getDeviceInfo(),
        version: await getVersionInfo(),
        clientType: getSendPlatformType(),
      ).toJson(),
    )
        .then((res) {
      if (res.success != null && res.success!) {
        // param = {
        //   GioUserParamKey.loginType_var: '验证码登录',
        //   GioUserParamKey.loginStatus_var: '登录成功',
        //   GioUserParamKey.loginSource_var: gioStr,
        // };
        // RikiEventTracker()
        //     .trackCustomEvent(GioUserEventSymbol.loginSucces, variable: param);

        // Provider.of<UserViewModel>(context!, listen: false).userLogin(res.result!);
        //替换为上面的方法
        //Global.saveUserAccount(res.result);
        RikiLoginGlobal.saveUserAccount(res.result);
        RikiLogin.instance.refreshUserLoginEntity(res.result!);
        RikiBase.setAccessToken(res.result!.accessToken!);
        Future.delayed(const Duration(seconds: 1), () {
          userLoginRecord();
          ToastUtil.showPositiveToast('登录成功');
          completer.complete();
        });

      } else {
        if (res.statusCode == 3602) {
          // 登陆过期
          // RikiApplication.eventBus.fire(BeOverdueEvent(res.message!));
        } else {
          ToastUtil.showNegativeToast(res.message);
        }
        completer.complete();
      }
    });
    return completer.future;
  }

  /// 发送验证码
  Future<void> sendSmsCodeFun(String neCaptchaValidate) {
    Completer completer = Completer();
    netEaseSendSmsApi.start(params: netEaseSendSmsApi.params(userPhone.trim().toString(), neCaptchaValidate, 1)).then((res) {
      if (res.success ?? false) {
        ToastUtil.showPositiveToast('验证码已发送，请注意查收!');
        startCountdown();
      } else {
        ToastUtil.showNegativeToast(res.message);
      }
      completer.complete();
    });
    return completer.future;
  }

  /// 60秒倒计时
  void startCountdown() {
    countdownTime = 60;
    sendCode = '($countdownTime)秒重发';
    notifyListeners(refreshVM: false);
    final call = (timer) {
      if (countdownTime < 1) {
        _timer?.cancel();
        _timer = null;
        sendCode = '重发';
      } else {
        countdownTime -= 1;
        sendCode = '($countdownTime)秒重发';
      }
      notifyListeners(refreshVM: false);
    };
    _timer = Timer.periodic(Duration(seconds: 1), call);
  }

  @override
  void dispose() {
    super.dispose();
    smsCheckCodeApi.cancel();
    netEaseSendSmsApi.cancel();
    _userLoginRecordApi.cancel();
    _timer?.cancel();
    _timer = null;
  }

  //获取设备信息
  Future<String> getDeviceInfo() async {
    DeviceInfoPlugin deviceInfo = new DeviceInfoPlugin();
    if (Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      return androidInfo.id;
    } else if (Platform.isIOS) {
      IosDeviceInfo iosInfo = await deviceInfo.iosInfo;
      return iosInfo.identifierForVendor;
    } else {
      return '';
    }
  }

  //获取哪个平台
  int getSendPlatformType() {
    return Platform.isAndroid ? 2 : 1;
  }

  //获取版本号
  Future<String> getVersionInfo() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    return packageInfo.version;
  }

  /// 告诉后台登录成功
  Future userLoginRecord() async {
    _userLoginRecordApi.start(params: {}).then((res) {});
  }

  @override
  Future loadData() {
    throw UnimplementedError();
  }

  @override
  onCompleted(data) {
    throw UnimplementedError();
  }
}
